/***************************************************************************
 *            login.c
 *
 *  mar mayo 31 16:47:09 2011
 *  Copyright  2011  Kellerman Rivero
 *  <user@host>
 ****************************************************************************/
/*
 * login.c
 *
 * Copyright (C) 2011 - Kellerman Rivero
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "login.h"
#define LOGIN_UI "src/login.ui"

extern char *oauth_token;
extern char *oauth_token_secret;
extern char *access_token_key;
extern char *access_token_secret;
extern char *username;
extern WidgetLogin *LoginWindow;

#define MODULE_NAME "api_twitter"

#include <curl/curl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <oauth.h>

typedef struct keejoo_file{
	char filename[MAX_FILENAME_LENGTH];
	FILE *data;
} k_file;


void get_token_in_parameters(char *reply, char **key, char **secret, char **username){
		int rc;
		int i;
		char **rv = NULL;
		rc = oauth_split_url_parameters(reply, &rv);		
		qsort(rv, rc, sizeof(char *), oauth_cmpstringp);

		for(i=0;i<rc;i++){
			
			if(!strncmp(rv[i],"oauth_token_secret=",18)) {
				*secret=strdup(&(rv[i][19]));
				if(DEBUG_MODE){
					debug_print (MODULE_NAME,"get_token_in_parameters","t_secret",*secret);
				}
			}else{
				if(!strncmp(rv[i],"oauth_token=",11)) {
					*key=strdup(&(rv[i][12]));
					if(DEBUG_MODE){
						debug_print (MODULE_NAME,"get_token_in_parameters","t_key",*key);
					}
				}else{
					if(!strncmp(rv[i],"screen_name=",11)){
						*username=strdup(&(rv[i][12]));
						if(DEBUG_MODE){
							debug_print (MODULE_NAME,"get_token_in_parameters","Username",*username);
						}
					}
				}
			}
			
		}

	 	if(rv) free(rv);
}


char* get_token(char *resource, char **key, char **secret, char *oauth_key, char *oauth_secret, char **username){
	char *postarg = NULL;
    char *req_url;
    char *reply;
	req_url = oauth_sign_url2(resource, &postarg, OA_HMAC, NULL, CONSUMER_KEY, CONSUMER_SECRET, oauth_key, oauth_secret);
	reply = oauth_http_post(req_url,postarg);	

	if(DEBUG_MODE){
		debug_print(MODULE_NAME,"get_token","req_url",req_url);
		debug_print(MODULE_NAME,"get_token","reply",reply);
	}
	
	get_token_in_parameters (reply,key,secret,username);
	
	if(req_url) free(req_url);
	if(postarg) free(postarg);
  	if(reply) free(reply);
	
	return NULL;
}


void get_authorize_url(char *oauth_token, char **authorize_url){
	strcpy(*authorize_url,AUTHORIZE_URL);
	strcat(*authorize_url,"?oauth_token=");
	strcat(*authorize_url,oauth_token);
	if(DEBUG_MODE) debug_print (MODULE_NAME,"get_authorize_url","authorize_url",*authorize_url);
}


void create_file_with_access_token (char username[MAX_USERNAME_LENGTH],char *access_token_key, char *access_token_secret){
	char filename[MAX_FILENAME_LENGTH];

	
	
	int length_key = strlen(access_token_key);
	int length_secret = strlen(access_token_secret);
	
	strcpy(filename,CREDENTIAL_PREFIX);
	strcat(filename,username);
	
	
	if(DEBUG_MODE){
		debug_print (MODULE_NAME,"create_file_with_access_token","username",username);
		debug_print (MODULE_NAME,"create_file_with_access_token","filename",filename);
	}
	FILE *f_credentials;
	f_credentials = fopen(filename,"w");

	fwrite(&length_key,sizeof(int),1,f_credentials);
	debug_print_int(MODULE_NAME,"create_file_with_access_token","length_key",length_key);
	fwrite(access_token_key,sizeof(char),length_key,f_credentials);
	
	fwrite(&length_secret,sizeof(int),1,f_credentials);
	debug_print_int(MODULE_NAME,"create_file_with_access_token","length_secret",length_secret);
	fwrite(access_token_secret,sizeof(char),length_secret,f_credentials);
	
	fclose(f_credentials);
}

int load_file_with_access_token(char username[MAX_FILENAME_LENGTH], char **access_token_key, char **access_token_secret){
	char filename[MAX_FILENAME_LENGTH];

	int *length_key = (int*)malloc(sizeof(int));
	int *length_secret = (int*)malloc(sizeof(int));

	
	
	
	strcpy(filename,CREDENTIAL_PREFIX);
	strcat(filename,username);

	if(DEBUG_MODE){
		debug_print (MODULE_NAME,"load_file_with_access_token","username",username);
		debug_print (MODULE_NAME,"load_file_with_access_token","filename",filename);
	}

	FILE *f_credentials;
	f_credentials = fopen(filename,"r");

	if(f_credentials){
		
		
		fread(length_key,sizeof(int),1,f_credentials);
		
		char *tmp_key = malloc(sizeof(char)*(*length_key));
		*access_token_key = malloc(sizeof(char)*(*length_key));
		
		fread(tmp_key,sizeof(char),*length_key,f_credentials);

		fread(length_secret,sizeof(int),1,f_credentials);
		char *tmp_secret = malloc(sizeof(char)*(*length_secret));
		*access_token_secret = malloc(sizeof(char)*(*length_secret));

		fread(tmp_secret,sizeof(char),*length_secret,f_credentials);
		if(DEBUG_MODE){
			
			debug_print_int (MODULE_NAME,"load_file_with_access_token","length_key",*length_key);
			debug_print_int (MODULE_NAME,"load_file_with_access_token","length_secret",*length_secret);
			
			debug_print(MODULE_NAME,"load_file_with_access_token","A_key",tmp_key);
			debug_print(MODULE_NAME,"load_file_with_access_token","A_secret",tmp_secret);
			strcpy(*access_token_key,tmp_key);
			strcpy(*access_token_secret,tmp_secret);
		}
		return 1;
	}
		return 0;	
}

static size_t write_data_to_file (void *buffer, size_t size, size_t nmemb, void *stream)
{
  k_file *outfile= (k_file *) stream;
  if(outfile && !outfile->data) {
    outfile->data = fopen(outfile->filename, "w");
    if(!outfile->data){
	  debug_print (MODULE_NAME,"write_data_to_file","Error!","Cannot open file to write");
      return -1; 
	}  
  }	
  return fwrite(buffer, size, nmemb, outfile->data);
}


WidgetLogin*
create_window_login (void)
{
	WidgetLogin *LoginWindow = (WidgetLogin*) malloc (sizeof(_WidgetLogin));
	
	GtkBuilder *builder;
	GError* error = NULL;

	/* Load UI from file */
	builder = gtk_builder_new ();
	if (!gtk_builder_add_from_file (builder, LOGIN_UI, &error))
	{
		g_warning ("Couldn't load builder file: %s", error->message);
		g_error_free (error);
	}

	/* Auto-connect signal handlers */
	gtk_builder_connect_signals (builder, NULL);
	
	/* Get the window object from the ui file */
	LoginWindow->Window = GTK_WIDGET (gtk_builder_get_object (builder, "LoginWindow"));
	LoginWindow->BtAutenticar = GTK_BUTTON(gtk_builder_get_object (builder, "BtAutenticar"));
	LoginWindow->TxtPIN = GTK_ENTRY(gtk_builder_get_object (builder, "TxtPIN"));
	get_token (REQUEST_TOKEN_URL,&oauth_token,&oauth_token_secret,NULL,NULL,NULL);
	//GtkBuilderConnectFunc (builder,LoginWindow->BtAutenticar,"clicked","BtAutenticar_Clicked",NULL,NULL,NULL);
	
	g_object_unref (builder);
	
	return LoginWindow;
}

void BtAutenticar_Clicked(GtkButton *object, gpointer user_data){
	gtk_button_set_label (object,"Autenticando");
	char *x= (char*)malloc(sizeof(char)*MAX_URL_LENGTH);
	get_authorize_url (oauth_token,&x);
	char open_url[MAX_FILENAME_LENGTH];
	strcpy(open_url,"gnome-open ");
	strcat(open_url,x);
	system(open_url);	
}

void BtLogin_Clicked(GtkButton *object, gpointer user_data){
	char *verifier= (char*) malloc(sizeof(char)*8);
	verifier = gtk_entry_get_text (LoginWindow->TxtPIN);
	char access_token_url[MAX_URL_LENGTH];
	strcpy(access_token_url,ACCESS_TOKEN_URL);
	strcat(access_token_url,"?oauth_verifier=");
	strcat(access_token_url,verifier);
	if(DEBUG_MODE) debug_print (MODULE_NAME,"BtLogin_Clicked","access_token_url",access_token_url);	
	get_token (access_token_url,&access_token_key,&access_token_secret,oauth_token,oauth_token_secret,&username);
	if(DEBUG_MODE) get_resource (UPDATE_STATUS_URL_TEST,access_token_key,access_token_secret);
	
}

void Destroy_Login_Window(GtkWidget *object, gpointer user_data){
	gtk_main_quit();
}


